<template>
  <div class="post-comment-container">
    <van-row>
      <van-col span="20">
        <van-cell-group class="textarea-wrap">
          <van-field
            v-model.trim="message"
            placeholder="请输入留言……"
            type="textarea"
            autosize
            maxlength="210"
            show-word-limit
          />
        </van-cell-group>
      </van-col>
      <van-col span="4" class="button-wrap">
        <van-button
          size="mini"
          type="info"
          @click="onPost"
          :disabled="!message"
        >发布</van-button>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import { addComment } from '../../api/comment'

export default {
  name: 'postComment',
  props: {
    // 如果是发布文章评论，则传递文章 ID
    // 如果是发布评论回复，则传递评论 ID
    target: {
      type: [Number, String, Object],
      required: true
    },
    // 如果是发布评论回复，则也需要传递文章 ID
    articleId: {
      type: [Number, String, Object],
      default: null
    }
  },
  data () {
    return {
      message: ''
    }
  },
  methods: {
    async onPost () {
      this.$toast.loading({
        message: '发布中……',
        forbidClick: true
      })
      const { data: { data: { new_obj: res } } } = await addComment({
        target: this.target.toString(), // 评论的目标id（评论文章即为文章id，对评论进行回复则为评论id）
        content: this.message,
        art_id: this.articleId ? this.articleId.toString() : null // 文章id，对评论内容发表回复时，需要传递此参数，表明所属文章id。对文章进行评论，不要传此参数
      })
      this.$emit('post-success', res)
      this.$toast.success('发布成功！')
      this.message = '' // 发布成功，清空文本框
    }
  }
}
</script>

<style scoped>
.van-row, .button-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
